package cn.nawang.ebeim.client.util;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.nawang.ebeim.client.bean.ClientConfiguration;
import cn.nawang.ebeim.client.bean.RecoveryTask;
import cn.nawang.ebeim.client.bean.StorageServer;
import cn.nawang.ebeim.client.bean.UpDownloadFailedBean;
import cn.nawang.ebeim.client.version.Node;
import cn.nawang.ebeim.common.entity.FileInfo;

public class TransportUtil {
  private static final Logger LOG = LoggerFactory.getLogger(TransportUtil.class);

  public static StorageServer getPreferredServer() {
    // return new StorageServer("127.0.0.1", 8844);
    List<StorageServer> servers = ClientConfiguration.getStorageServers();
    if (!servers.isEmpty()) {
      int r = new Random().nextInt(servers.size());
      StorageServer s = servers.get(r);
      return s;
    }
    return null;
  }


  public static void downloadVersionTree(String dsId, String version) {
    LOG.debug("TODO - downloadVersionTree:{}", version);
    StorageServer server = getPreferredServer();
    if (server == null) {
      LOG.error("no storage server to connect to");
      return;
    }
    LOG.debug("Storage Server: {}", server);
    cn.nawang.ebeim.client.transfer.Client client =
        new cn.nawang.ebeim.client.transfer.Client(server.getHost(), server.getPort());
    FileInfo info = new FileInfo();
    info.setType(FileInfo.TYPE_VERSION_DOWNLOAD);
    info.setDataId(dsId);
    info.setVersion(version);
    try {
      client.doTask(info);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static boolean downloadDataFile(RecoveryTask task, String signature,Node node) {
    LOG.debug("TODO - downloadDataFile:{}", signature);
    StorageServer server = getPreferredServer();
    if (server == null) {
      LOG.info("no storage server to connect to");
      return false;
    }
    LOG.debug("Storage Server: {}", server);
    cn.nawang.ebeim.client.transfer.Client client =
        new cn.nawang.ebeim.client.transfer.Client(server.getHost(), server.getPort());
    FileInfo info = new FileInfo();
    info.setType(FileInfo.TYPE_FILE_DOWNLOAD);
    info.setDataId(task.getDataSourceId());
    info.setSignature(signature);
    info.setNid(task.getNid());

    try {
      client.doTask(info);
      DbUpDownloadUtil.updateDownloadProcessBarOkSum(info.getNid());
      return true;
    } catch (Exception e) {
        DbUpDownloadUtil.updateDownloadProcessBarErrorSum(info.getNid());
        
        UpDownloadFailedBean bean = new UpDownloadFailedBean();
        bean.setUid(task.getCreateUserId());
        bean.setDsId(info.getDataId());
        bean.setNid(info.getNid());
        bean.setRoot("");
        bean.setPath(node.getPath());
        bean.setName(node.getName());
        bean.setRecoveryPath(task.getRecoveryPath());
        bean.setSignature(info.getSignature());
        bean.setType(DbUpDownloadFailedUtil.FAILED_DOWNLOAD);
        bean.setStatus(DbUpDownloadFailedUtil.STATUS_NEW);
        bean.setTime(new Date().getTime());
        bean.setIsEncrypt(task.getIsEncrypt());
        DbUpDownloadFailedUtil.addUpDownloadFailed(bean);
//      if (task.getTryCount() < PropertiesConstants.TRY_COUNT) {
//          LOG.info("第"+task.getTryCount()+"次重试----"+e.getMessage());
//        task.setTryCount(task.getTryCount() + 1);
//        try {
//          return downloadDataFile(task, signature);
          // client.doTask(info);//文件级别
          // RecoveryQueue.enqueue(task);//文件夹级别
//        } catch (Exception e1) {
//          e.printStackTrace();
//          LOG.info(e.getMessage());
//        }
//      } else {
        LOG.info("重试超过3次，下载失败-----"+e.getMessage());
        e.printStackTrace();
        return false;
//      }
    }
//    return false;
  }

  public static void uploadVersionTree(String dsId, String version, String path) throws Exception {
    LOG.debug("TODO - uploadVersionTree:{}", path);
    StorageServer server = getPreferredServer();
    if (server == null) {
      CommonMethodsUtils.reGetServer();
    }
    LOG.debug("Storage Server: {}", server);
    cn.nawang.ebeim.client.transfer.Client client =
        new cn.nawang.ebeim.client.transfer.Client(server.getHost(), server.getPort());
    FileInfo info = new FileInfo();
    info.setType(FileInfo.TYPE_VERSION_UPLOAD);
    info.setDataId(dsId);
    info.setVersion(version);
    info.setPath(path);
    client.doTask(info);
  }

  public static void uploadDataFile(String dsId, String signature, String path,String[] pathArr) throws Exception {
    LOG.debug("TODO - uploadDataFile: {}", path);
    StorageServer server = getPreferredServer();
    if (server == null) {
      CommonMethodsUtils.reGetServer();
      server = getPreferredServer();
    }
    if (server == null) {
        LOG.info("Storage Server is null", server);
        throw new Exception("server is null");
    }
    
    LOG.debug("Storage Server: {}", server);
    cn.nawang.ebeim.client.transfer.Client client =
        new cn.nawang.ebeim.client.transfer.Client(server.getHost(), server.getPort());
    FileInfo info = new FileInfo();
    info.setType(FileInfo.TYPE_FILE_UPLOAD);
    info.setDataId(dsId);
    info.setPath(path);
    info.setSignature(signature);

    File f = new File(path);
    if (f.exists() && f.canRead()) {
      client.doTask(info);
    } else {
      if (info.getNid() != null) {
        UploadProcessBarList.summationTotal(info.getNid(), f.length());
        DbUpDownloadUtil.updateUploadProcessBarErrorSum(dsId);
        
        UpDownloadFailedBean bean = new UpDownloadFailedBean();
        bean.setDsId(dsId);
        bean.setRoot(pathArr[0]);
        bean.setPath(pathArr[1]);
        bean.setName(pathArr[2]);
        bean.setSignature(info.getSignature());
        bean.setType(DbUpDownloadFailedUtil.FAILED_UPLOAD);
        bean.setStatus(DbUpDownloadFailedUtil.STATUS_NEW);
        bean.setTime(new Date().getTime());
        bean.setUid(Integer.valueOf(pathArr[3]));
        bean.setIsEncrypt(pathArr[4]);
        DbUpDownloadFailedUtil.addUpDownloadFailed(bean);
        
      }
    }
  }
}
